using Infrastructure.Attribute;
using Infrastructure.Extensions;
using JTZY.Model.Pay.Dto;
using JTZY.Model.Pay;
using JTZY.Repository;
using JTZY.Service.Pay.IPayService;
using Infrastructure;
using Infrastructure.Enums;
using JTZY.Model.Order;
using Microsoft.AspNetCore.Http;
using JTZY.Model.Enum;
using WANFT.Utils;
using JTZY.Model.System;
using static JTZY.Common.GlobalEnumVars;
using JTZY.Common;
using Essensoft.Paylink.WeChatPay.V2.Request;
using Essensoft.Paylink.WeChatPay.V2;
using Essensoft.Paylink.WeChatPay;
using Newtonsoft.Json.Linq;
using JTZY.Infrastructure.CustomException;

namespace JTZY.Service.Pay
{
    /// <summary>
    /// 支付单表Service业务层处理
    /// </summary>
    [AppService(ServiceType = typeof(ICorecmsbillpaymentsService), ServiceLifetime = LifeTime.Transient)]
    public class CorecmsbillpaymentsService : BaseService<Corecmsbillpayments>, ICorecmsbillpaymentsService
    {

        private readonly IHttpContextAccessor _httpContextAccessor;

        public CorecmsbillpaymentsService(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
        }

        /// <summary>
        /// 查询支付单表列表
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        public PagedInfo<CorecmsbillpaymentsDto> GetList(CorecmsbillpaymentsQueryDto parm)
        {
            var predicate = QueryExp(parm);

            var response = Queryable()
                .Where(predicate.ToExpression())
                .ToPage<Corecmsbillpayments, CorecmsbillpaymentsDto>(parm);

            return response;
        }


        /// <summary>
        /// 获取详情
        /// </summary>
        /// <param name="PaymentId"></param>
        /// <returns></returns>
        public Corecmsbillpayments GetInfo(string PaymentId)
        {
            var response = Queryable()
                .Where(x => x.PaymentId == PaymentId)
                .First();

            return response;
        }

        /// <summary>
        /// 添加支付单表
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public Corecmsbillpayments AddCorecmsbillpayments(Corecmsbillpayments model)
        {
            return Insertable(model).ExecuteReturnEntity();
        }

        /// <summary>
        /// 修改支付单表
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int UpdateCorecmsbillpayments(Corecmsbillpayments model)
        {
            return Update(model, true);
        }

        public async Task<Corecmsbillpayments> Pay(string orderId, string payment_code, long userId, int payment_type,string barCode)
        {
            var order = await Context.Queryable<Corecmsorder>().Where(o => o.OrderId == orderId&&o.PayStatus==(int)OrderPayStatus.No).FirstAsync();
            if (order == null)
            {
                return null;
            }

            var billPayments = new Corecmsbillpayments();
            billPayments.PaymentId = CommonHelper.GetSerialNumberType((int)SerialNumberType.支付单编号);
            billPayments.SourceId = orderId;
            billPayments.Money = order.OrderAmount;
            billPayments.UserId = userId;
            billPayments.Type = 1;
            billPayments.Status = (int)BillPaymentsStatus.NoPay;
            billPayments.PaymentCode = payment_code;
            billPayments.Ip = _httpContextAccessor.HttpContext?.Connection.RemoteIpAddress != null ? _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString() : "127.0.0.1";
            billPayments.Parameters = "";
            billPayments.CreateTime = DateTime.Now;

            int id = await InsertReturnIdentityAsync(billPayments);
            if (billPayments.Money == 0)
            {
                //更新订单信息
                //await Context.Updateable<>UpdateAsync(billPayments.PaymentId, (int)GlobalEnumVars.BillPaymentsStatus.Payed, billPayments.paymentCode, billPayments.money, "金额为0，自动支付成功", "");
                billPayments.Status = (int)BillPaymentsStatus.Payed;
                await UpdateAsync(billPayments);
                await Context.Updateable<Corecmsorder>()
                .SetColumns(t => new Corecmsorder() { PayStatus = 2, UpdateTime = DateTime.Now, PaymentTime = DateTime.Now })
                .Where(o => o.OrderId == order.OrderId).ExecuteCommandAsync();
                return billPayments;
            }
            else
            {
                var notifyUrl = "";// config.notifyUrl.EndsWith("/") ? config.notifyUrl + "m-" + config.appId : config.notifyUrl + "/m-" + config.appId;


                var orderRequest = new PayInfo()
                {
                    z_tp_bank_url = "https://pay.zgjindoufu.com",
                    z_tp_mchno = "2024111917230667372",
                    z_tp_operid = "15511",
                    z_tp_termid = "202412021147",
                    out_trade_no = billPayments.PaymentId,
                    total_amount = billPayments.Money.ToString("0.00"),
                    notify_url = notifyUrl,
                    z_tp_key = "88888888",
                    auth_code=barCode
                };

                var response = new PayRetInfo();

                WANFT_Util.BarcodePay(orderRequest, response);

                //var response = await _client.ExecuteAsync(orderRequest, payOptions);
                if (response.code == PayReturnCode.SUCCESS.ToString())
                {
                    billPayments.Status = (int)BillPaymentsStatus.Payed;
                    await UpdateAsync(billPayments);
                    await Context.Updateable<Corecmsorder>()
.SetColumns(t => new Corecmsorder() { PayStatus = 2, UpdateTime = DateTime.Now, PaymentTime = DateTime.Now,PayedAmount= billPayments.Money })
.Where(o => o.OrderId == order.OrderId).ExecuteCommandAsync();
                    return billPayments;

                }
                else
                {
                    return billPayments;

                }
            }


        }

        public async Task<Corecmsbillpayments> Query(string orderId, string paymentId, long userId, int payment_type)
        {
            var order = await Context.Queryable<Corecmsorder>().Where(o => o.OrderId == paymentId).FirstAsync();
            if (order == null)
            {
                return null;
            }

            var billPayments = await Context.Queryable<Corecmsbillpayments>().Where(o => o.PaymentId == orderId).FirstAsync();

            if (billPayments == null)
            {
                return null;
            }


            var orderRequest = new PayInfo()
            {
                z_tp_bank_url = "https://pay.zgjindoufu.com",
                z_tp_mchno = "2024111917230667372",
                z_tp_operid = "15511",
                z_tp_termid = "202412021147",
                out_trade_no = billPayments.PaymentId,
                z_tp_key = "88888888"
            };

            var response = new PayRetInfo();

            WANFT_Util.OrderQuery(orderRequest, response);

            //var response = await _client.ExecuteAsync(orderRequest, payOptions);
            if (response.code == PayReturnCode.SUCCESS.ToString())
            {
                billPayments.Status = (int)BillPaymentsStatus.Payed;
                await UpdateAsync(billPayments);
                await Context.Updateable<Corecmsorder>()
.SetColumns(t => new Corecmsorder() { PayStatus = 2, UpdateTime = DateTime.Now, PaymentTime = DateTime.Now })
.Where(o => o.OrderId == order.OrderId).ExecuteCommandAsync();
                return billPayments;

            }
            else
            {
                return billPayments;

            }



        }

        //public async Task<WebApiCallBack> Refund(Corecmsbillrefund refundInfo, Corecmsbillpayments paymentInfo)
        //{
        //    var jm = new WebApiCallBack();

        //    var tradeType = WeiChatPayTradeType.JSAPI.ToString();
        //    if (!string.IsNullOrEmpty(paymentInfo.Parameters))
        //    {
        //        var jObj = (JObject)JsonConvert.DeserializeObject(paymentInfo.Parameters);
        //        if (jObj != null && jObj.TryGetValue("trade_type", out var value))
        //            tradeType = PayHelper.GetWeiChatPayTradeType(value.ObjectToString());
        //    }

        //    var config = await _weChatPayConfigServices.Queryable().Where(p => p.MchId == paymentInfo.MchId
        //        && p.IsEnable == true && p.AppType == tradeType).FirstAsync();
        //    if (config == null)
        //    {
        //        jm.msg = "支付配置信息获取失败";
        //        return jm;
        //    }

        //    if (string.IsNullOrEmpty(config.RefundUrl))
        //    {
        //        jm.msg = "未获取到配置的退款通知地址";
        //        return jm;
        //    }

        //    //构建linkPay请求配置实体
        //    var payOptions = new WeChatPayOptions
        //    {
        //        AppId = config.AppId,
        //        MchId = config.MchId,
        //        APIKey = config.ApiKey,
        //        APIv3Key = config.ApiV3Key,
        //        Certificate = config.Certificate,
        //        RsaPublicKey = config.RsaPublicKey,
        //        SubAppId = config.SubAppId,
        //        SubMchId = config.SubMchId
        //    };

        //    var notifyUrl = config.RefundUrl.EndsWith("/") ? config.RefundUrl + "m-" + config.MchId : config.RefundUrl + "/m-" + config.MchId;

        //    var request = new WeChatPayRefundRequest
        //    {
        //        OutRefundNo = refundInfo.RefundId,
        //        TransactionId = paymentInfo.TradeNo,
        //        OutTradeNo = paymentInfo.PaymentId,
        //        TotalFee = Convert.ToInt32(paymentInfo.Money * 100),
        //        RefundFee = Convert.ToInt32(refundInfo.Money * 100),
        //        NotifyUrl = notifyUrl
        //    };
        //    var response = await _client.ExecuteAsync(request, payOptions);

        //    if (response.ReturnCode == WeChatPayCode.Success && response.ResultCode == WeChatPayCode.Success)
        //    {
        //        jm.status = true;
        //        jm.msg = "退款成功";
        //        jm.data = response;
        //    }
        //    else
        //    {
        //        jm.status = false;
        //        jm.msg = "退款失败：" + response.ErrCodeDes;
        //        jm.data = response;
        //    }

        //    return jm;
        //}

        /// <summary>
        /// 查询导出表达式
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        private static Expressionable<Corecmsbillpayments> QueryExp(CorecmsbillpaymentsQueryDto parm)
        {
            var predicate = Expressionable.Create<Corecmsbillpayments>();

            return predicate;
        }
    }
}